import React, { useCallback, useState, useContext } from 'react';
import StuContext from '../store/StuContext';
import StudentForm from './StudentForm';
import useFetch from '../hooks/useFetch';
const URL = 'http://localhost:1337/api/students/'
const Student = ({ stu, stuId }) => {
    // {stu:{name, age, gender, address}} = props

    const stuCtx = useContext(StuContext)

    // //添加一个state来记录数据是否正在加载
    // const [loading, setLoading] = useState(false)
    // //创建一个state来记录是否数据请求失败
    // const [errorMsg, setErrorMsg] = useState(null)
    //记录是否是在修改
    const [isEdit, setIsEdit] = useState(false)
    const { data,
        loading,
        errorMsg,
        fetchData: delStu } = useFetch({
            url: `students/${stuId}`,
            method: 'delete'

        }, stuCtx.fetchData)
    // const delStu = useCallback(async (id) => {
    //     try {
    //         setLoading(true)
    //         setErrorMsg(null)
    //         const res = await fetch(URL + id, {
    //             method: 'delete'
    //         })
    //         if (!res.ok) {
    //             throw new Error('删除数据失败')
    //         }
    //         //删除成功后触发列表刷新
    //         stuCtx.fetchData()
    //     } catch (e) {
    //         setErrorMsg(e.message)
    //     } finally {
    //         setLoading(false)
    //     }

    // }, [])

    const deleteHandler = (id) => {
        //删除学生
        delStu(id)

    }
    const cancelEdit = () => {
        setIsEdit(false)
    }
    return (
        <>
            {!isEdit &&
                <tr>
                    <td>{stu.name}</td>
                    <td>{stu.gender}</td>
                    <td>{stu.age}</td>
                    <td>{stu.address}</td>
                    <td>
                        <button onClick={() => deleteHandler(stuId)}>删除</button>
                        <button onClick={() => { setIsEdit(true) }}>修改</button>
                    </td>
                </tr>}
            {isEdit && <StudentForm stu={stu} cancelEdit={cancelEdit} stuId={stuId} />}
            {loading && <tr> <td colSpan={5}>数据正在删除中</td></tr>}
            {errorMsg && <tr> <td colSpan={5}>{errorMsg}</td></tr>}
        </>

    );
};

export default Student;
